<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ActiveRule;
use App\Models\Game\EventList;
use App\Models\Game\Server;
use App\Services\RedisService;
use App\Utils\MyLog;
use App\Utils\ResponseUtil;
use Illuminate\Support\Facades\DB;
use Predis\Command\Redis\ACL;

class ServerController extends Controller
{
    private RedisService $RedisService;

    /**
     * ServerController constructor.
     * @param RedisService $RedisService
     */
    public function __construct(RedisService $RedisService)
    {
        $this->RedisService = $RedisService;
    }

    public function paginate()
    {
        $model = Server::query();
        $page = request()->get('page',1);
        $pageSize = request()->get('limit',20);
        $paginate = $model->with('group')->orderByRaw('CAST(server_id AS UNSIGNED) ASC')->paginate($pageSize,'*','page',$page);
        $data = $paginate->items();
        $res = [];
        $res['code'] = 0;
        $res['count'] = $paginate->total();
        $res['data'] = $data;
        return ResponseUtil::json($res);
    }


    public function serverList()
    {
        $groups = request()->get('groups');
        if($groups){}
        MyLog::info('选择服务器分组'.json_encode($groups));
        $services = Server::query()->whereIn('group_id',$groups)->select('server_id','name','can_push')->orderByRaw('CAST(server_id AS UNSIGNED) ASC')->get()->toArray();
        $res = [];
        $res['code'] = 0;
        $res['data'] = $services;
        return ResponseUtil::json($res);
    }


    public function add() {
        // 开始数据库事务
        DB::beginTransaction();

        try {
            $data = request()->only(['server_id', 'name', 'server_info', 'group_id', 'login_ip', 'login_port', 'push_url', 'pay_status', 'show', 'busy_status', 'can_push', 'mysql_game_data_can_use', "is_merge"]);
            $data['created_at'] = date("Y-m-d H:i:s");

            // 插入 Server 数据
            Server::query()->insert($data);

            // 同步到 active_rule 将分组 ID 和对应分组的服务器 ID 同步.
            $groupid = request()->get('group_id');
            $newServerId = request()->get('server_id');

            MyLog::info('新增了对应分组的服务器');
            // 查询所有 active_rule 数据
            $activeRules = ActiveRule::query()->get();

            foreach ($activeRules as $activeRule) {
                // 获取现有的 groupids
                $groupIds = explode(',', $activeRule->serverGroup); // 将 groupids 转换为数组
                MyLog::info('处理过的付分组ID'.json_encode($groupIds));

                // 检查传入的 $groupid 是否存在于 groupIds 中
                if (in_array($groupid, $groupIds)) {
                    MyLog::info('存在已经有对应付分组的ID');

                    // 获取现有的 ServerList
                    $serverList = $activeRule->ServerList;
                    MyLog::info('当前排期表对应付分组的服务器ID: ' . json_encode($serverList));

                    // 将 ServerList 转换为数组，如果为 NULL 则初始化为空数组
                    $existingServers = $serverList ? explode(',', $serverList) : [];

                    // 检查新的 server_id 是否已经存在
                    if (!in_array($newServerId, $existingServers)) {
                        // 如果不存在，则添加新的 server_id
                        $existingServers[] = $newServerId;
                        MyLog::info('最终存入的值: ' . json_encode(implode(',', $existingServers)));

                        // 更新 ServerList
                        $activeRule->ServerList = implode('*', $existingServers);
                        $activeRule->save(); // 保存更新
                    }
                }
            }

            // 提交事务
            DB::commit();
            return ResponseUtil::success();

        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            MyLog::error('操作失败: ' . $e->getMessage());
            return ResponseUtil::fail('操作失败');
        }
    }

    public function detail($id){
        $data = Server::query()->where('server_id',$id)->first();
        return ResponseUtil::success($data);
    }

    public function editServer($id){
        $data = request()->only(['status']);
        $data['updated_at'] = date("Y-m-d H:i:s");
        $idArray=[];
        if (strpos($id, ',') !== false) {
            $idArray = explode(',', $id);
        }else{
            $idArray[] = $id;
        }
        MyLog::info('查看传入的ID'.json_encode($idArray));
        $b = Server::query()->whereIn('server_id',$idArray)->update($data);
        if ($b){
            return ResponseUtil::success();
        } else {
            return ResponseUtil::error();
        }
    }

    public function edit($id){
        DB::beginTransaction();
        try {
        $data = request()->only(['server_id','name','server_info','group_id','push_url','login_ip','login_port','show','busy_status','pay_status','status',
            'maintain_at','enable_at','can_push','mysql_game_data_can_use','is_merge']);
        $data['updated_at'] = date("Y-m-d H:i:s");
        $data1=$data['status'];
        MyLog::info('前端傳入數據'.json_encode($data));
        $b = Server::query()->where('server_id',$id)->update($data);
        $groupid = request()->get('group_id');
        $newServerId = request()->get('server_id');

        if ($b) {
            // 从 active_rule 中移除旧的 group_id 中的 server_id
            $activeRulesOld = ActiveRule::query()->get(); // 查询所有记录

            foreach ($activeRulesOld as $activeRule) {
                // 获取现有的 groupids
                $groupIds = explode('*', $activeRule->groupids); // 将 groupids 转换为数组

                // 检查传入的 $groupid 是否存在于 groupIds 中
                if (in_array($groupid, $groupIds)) {
                    // 获取现有的 ServerList
                    $serverList = $activeRule->ServerList;

                    // 将 ServerList 转换为数组
                    $existingServers = explode('*', $serverList);

                    // 检查并移除 server_id
                    if (in_array($newServerId, $existingServers)) {
                        $existingServers = array_filter($existingServers, function($id) use ($newServerId) {
                            return $id !== $newServerId; // 移除对应的 server_id
                        });

                        // 更新 ServerList
                        $activeRule->ServerList = implode('*', $existingServers);
                        $activeRule->save(); // 保存更新
                    }
                }
            }

            // 添加新的 group_id 中的 server_id（如果尚不存在）
            $activeRulesNew = ActiveRule::query()->get(); // 查询所有记录

            foreach ($activeRulesNew as $activeRule) {
                // 获取现有的 groupids
                $groupIds = explode('*', $activeRule->groupids); // 将 groupids 转换为数组

                // 检查传入的 $groupid 是否存在于 groupIds 中
                if (in_array($groupid, $groupIds)) {
                    // 获取现有的 ServerList
                    $serverList = $activeRule->ServerList;

                    // 将 ServerList 转换为数组
                    $existingServers = explode('*', $serverList);

                    // 检查新的 server_id 是否已经存在
                    if (!in_array($newServerId, $existingServers)) {
                        // 如果不存在，则添加新的 server_id
                        $existingServers[] = $newServerId;

                        // 更新 ServerList
                        $activeRule->ServerList = implode('*', $existingServers);
                        $activeRule->save(); // 保存更新
                    }
                }
            }

            // 提交事务
            DB::commit();
            return ResponseUtil::success();
        } else {
            return ResponseUtil::error();
        }
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            MyLog::error('操作失败: ' . $e->getMessage());
            return ResponseUtil::fail('操作失败');
        }
    }

    public function delete($id){
        Server::query()->where('server_id',$id)->delete();
        return ResponseUtil::success();
    }

    public function maintain($id){
        $array = [
            300,270,240,210,180,150,120,90,/*60,30,*/ //倒数5分 ~ 倒数1分 ， 每30秒发送一次
            60,50,40,30,20,10,            //倒数60秒 ~ 倒数10秒 ， 每10秒发送一次
            // 9,8,7,6,5,4,3,2,1             //倒数10秒 ~ 0秒 ， 每一秒发送一次
        ];

        $maintainAt = request()->get('maintain_at'); //维护时间，维护时间到期后，调用API关闭服务器
        $endTimestamp = strtotime($maintainAt);

        if (strpos($id, ',') !== false) {
            $idArray = explode(',', $id);
            $servers = Server::whereIn('server_id', $idArray)->where('is_merge',0)
                ->get();
         Server::whereIn('server_id', $idArray)->update(['maintain_at' => date("Y-m-d H:i:s",$endTimestamp)]);
            ;
            foreach ($servers as $server) {
                $serverId = data_get($server, 'server_id');
                foreach($array as $second){
                    $tempTime = $endTimestamp - $second;
                    EventList::query()->insert([
                        'created_at'=>date("Y-m-d H:i:s"),
                        'message'=>"服务器即将维护,将于". $this->showCharTime($second) ."后关闭",
                        'event_type'=>1,
                        'server_id'=>$serverId,
                        'execute_at'=>date("Y-m-d H:i:s",$tempTime)
                    ]);
                }
                EventList::query()->insert([
                    'created_at'=>date("Y-m-d H:i:s"),
                    'message'=>"",
                    'event_type'=>0,
                    'server_id'=>$serverId,
                    'execute_at'=>date("Y-m-d H:i:s",$endTimestamp)
                ]);

                $server->maintain_at = date("Y-m-d H:i:s",$endTimestamp);
                $server->save();
            }
        }else{
            $server = Server::query()->where('server_id',$id)->first();
        $serverId = data_get($server,'server_id');


        foreach($array as $second){
            $tempTime = $endTimestamp - $second;
            EventList::query()->insert([
                'created_at'=>date("Y-m-d H:i:s"),
                'message'=>"服务器即将维护,将于". $this->showCharTime($second) ."后关闭",
                'event_type'=>1,
                'server_id'=>$serverId,
                'execute_at'=>date("Y-m-d H:i:s",$tempTime)
            ]);
        }

        EventList::query()->insert([
            'created_at'=>date("Y-m-d H:i:s"),
            'message'=>"",
            'event_type'=>0,
            'server_id'=>$serverId,
            'execute_at'=>date("Y-m-d H:i:s",$endTimestamp)
        ]);

        $server->maintain_at = date("Y-m-d H:i:s",$endTimestamp);
        $server->save();
        }
        return ResponseUtil::success();
    }


    private function showCharTime($seconds){
        $minute = floor($seconds / 60);
        $second = $seconds % 60;
        return "{$minute}分{$second}秒";
    }

    /** 终止维护
     * @param $id
     */
    public function stopMaintain($id)
    {
        if (strpos($id, ',') !== false) {
            $idArray = explode(',', $id);
            $servers = Server::whereIn('server_id', $idArray)->get();
            foreach ($servers as $server) {
                $serverId = data_get($server, 'server_id');
                EventList::query()->where('server_id',$serverId)->whereIn('event_type',[0,1])->delete();
                $server->save();
            }
        }else{
        $server = Server::query()->where('server_id',$id)->first();
        $serverId = data_get($server,'server_id');

            EventList::query()->where('server_id',$serverId)->whereIn('event_type',[0,1])->delete();
            $server->save();
        }
        return ResponseUtil::success();
    }

}
